package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    //批量添加预约设置数量方法
    public void addOrderSettings(List<OrderSetting> orderSettingList) {

        if (orderSettingList != null && orderSettingList.size() > 0) {
            for (OrderSetting orderSetting : orderSettingList) {

                //根据日期查询是否设置过预约人数,若设置,则更新预约人数,未设置则添加
                this.addOrEditOrderSettingByDate(orderSetting);
            }

        }
    }


    //根据年-月,查询该月份的预约设置信息方法
    public List<Map> getOrderSettingByYearAndMonth(String date) {//2020-8
        //统一设置当前月的日期范围   根据1-31日期范围查询预约设置数据
        String dateBegin = date + "-1";//2020-8-1
        String dateEnd = date + "-31";//2020-8-31

        //创建map集合,存储日期范围,便于传递参数查询数据库
        Map dateMap = new HashMap<>();
        dateMap.put("dateBegin", dateBegin);
        dateMap.put("dateEnd", dateEnd);

        //调用数据层查询预约设置方法
        List<OrderSetting> orderSettingList = orderSettingDao.getOrderSettingByYearAndMonth(dateMap);

        //定义嵌套map的list集合类,用于封装返回前端数据
        //返回数据格式为  { date: 1, number: 120, reservations: 1 } 的集合
        List<Map> orderSettingMapList = new ArrayList<>();

        for (OrderSetting orderSetting : orderSettingList) {
            Map orderSettingMap = new HashMap<>();

            orderSettingMap.put("date", orderSetting.getOrderDate().getDate());//获得日期(几号)
            orderSettingMap.put("number", orderSetting.getNumber());//获得预约人数
            orderSettingMap.put("reservations", orderSetting.getReservations());//获得已预约人数

            orderSettingMapList.add(orderSettingMap);
        }
        return orderSettingMapList;
    }

    //根据日期修改预约人数
    public void editNumberByDate(OrderSetting orderSetting) {
        this.addOrEditOrderSettingByDate(orderSetting);
    }

    //根据日期查询是否设置过预约人数,若设置,则更新预约人数,未设置则添加
    public void addOrEditOrderSettingByDate(OrderSetting orderSetting) {

        //检查该数据日期是否存在
        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());

        if (count > 0) {
            //已经存在执行更新操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
            //不存在 执行添加操作 在t_ordersetting表中
            orderSettingDao.addOrderSetting(orderSetting);
        }
    }
}
